package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author Waker
 * @description:
 * @create 2025-09-02-9:41
 */
@RequestMapping("/upload")
@RestController
@Slf4j
public class UploadController {
    //在配置类OssConfiguration中定义了AliOssUtil的@Bean方法aliOssUtil 所以这里可以依赖注入
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping
    public Result upload(MultipartFile file){
        log.info("文件上传：{}",file);

        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀 dfdfdf.png
            //通过最后一个 . 截取
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用UUID 构造新文件的名称 防止重复
            String objectName = UUID.randomUUID().toString() + extension;
            //文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            //文件访问路径规则 https://BucketName.Endpoint/ObjectName
            //https://sky-take-out-234817.oss-cn-beijing.aliyuncs.com/a5a58772-b947-4ec0-98d0-1b3ff34711d4.png
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：",e);
        }
        return Result.error("文件上传失败");
    }
}
